﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Raven.Abstractions.Data;
using Raven.Client.Connection;
using Raven.Json.Linq;

namespace TimeTracker.Persistence
{
    public static class RavenExtensions
    {
        public static void CreateDatabase(this IDatabaseCommands self, string name, DatabaseDocument database)
        {
            self = self.GetRootDatabase();

            var doc = RavenJObject.FromObject(database);

            var docId = "Raven/Databases/" + name;
            if (self.Get(docId) != null)
                return;

            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                self.Put(docId, null, doc, new RavenJObject());
            }
        }

        public static void CreateInMemoryDatabase(this IDatabaseCommands self, string name)
        {
            self.CreateDatabase(name, new DatabaseDocument
            {
                Settings = { { "Raven/RunInMemory", "true" } }
            });
        }

        public static bool DeleteDatabase(this IDatabaseCommands self, string name)
        {
            self = self.GetRootDatabase();

            var docId = "Raven/Databases/" + name;

            if (self.Get(docId) == null)
                return false;

            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                self.Delete(docId, null);
            }

            return true;
        }
    }
}
